const WebSocket = require("ws")
const User = require("../controller/User")
const wss = new WebSocket.Server({ port: config.wsPort })
const fileModel = require("../model/File")
const ws = {
  connect() {
    wss.on("connection", (client, req) => {
      client.on("message", (data) => {
        if (data === "ping") {
          client.send("pong")
        } else {
          data = JSON.parse(data)
          if(data.userId){
            client.id = data.userId
          }  
        }
      })
      client.on("close",async (data) => {
        try {
           await fileModel.update({
            occupyUserId:null
          },{
            where:{
              occupyUserId:client.id
            }
          })
        } catch (e) {
          console.log(e)
        }
      })
    })
  },
  // 点对点发送消息
  send(clientId, message) {
    const clients = Array.from(wss.clients)
    for (let client of clients) {
      if (client.id == clientId) {
        client.send(message)
        break
      }
    }
  },
  // 广播消息
  broadcast(message) {
    const clients = Array.from(wss.clients)
    for (let client of clients) {
      client.send(message)
    }
  },
}

module.exports = ws
